<template>
  <sv-page>
    <view class="exam-fav">
      <view class="sv-paging-header">
        <uv-tabs
          :list="tabList"
          keyName="lib_name"
          activeStyle="color:#0081ff"
          inactiveStyle="color:#1cbbb4"
          @click="tapTab"
        >
          <template #right>
            <text
              v-if="editList.length > 0"
              class="cuIcon-delete text-xl text-red padding-sm"
              @click="onDelete"
            ></text>
            <text
              class="cuIcon-edit text-xl padding-sm"
              :class="[isEdit ? 'text-blue' : 'text-cyan']"
              @click="onEdit"
            ></text>
          </template>
        </uv-tabs>
      </view>
      <view class="sv-paging-list">
        <sv-paging
          ref="pagingRef"
          :apiFunc="favExamList"
          :apiParams="dataParams"
          @apiQuery="queryRes"
          @refreshOK="refreshOK"
        >
          <template #default="{ data }">
            <view class="fav-exam-card" :class="[isEdit ? 'shake-bottom' : '']">
              <view class="fav-exam-item">
                <view class="fav-exam-item-title flex-vc">
                  <view class="flex-sub flex-vc">
                    <sv-checkbox
                      v-if="isEdit"
                      class="margin-right-sm"
                      :info="data.item.exam_id"
                      @change="changeCheck"
                    ></sv-checkbox>
                    <text>题库：</text>
                    <text class="text-blue">{{ libMap[data.item.from_lib] }}</text>
                    <text class="text-cyan margin-left-sm">{{ libMap[data.item.unit] }}</text>
                  </view>
                  <view class="type-tag">
                    {{ examConfig.paperTypeDict[data.item.exam_type] }}
                  </view>
                </view>
                <view @click="onExam(data.item, data.index)">
                  <mp-html :content="data.item.exam_name" />
                </view>
              </view>
            </view>
          </template>
        </sv-paging>
      </view>
    </view>
  </sv-page>
</template>

<script setup>
import { ref } from 'vue'
import { onLoad } from '@dcloudio/uni-app'
import { store } from '@/uni_modules/sv-id-pages/common/store'
import { buyLibList, favExamDelete, favExamList } from '@/service/api/record'
import { cloneDeep } from 'lodash-es'
import examConfig from '@/uni_modules/sv-exam-plus/config.js'

const dataParams = ref({ user_id: store.userInfo._id })
const favExamData = ref([])
const libMap = ref({})
const tabList = ref([])
const pagingRef = ref()

onLoad(async () => {
  uni.showLoading({ title: '加载中' })
  await handleInit()
  uni.hideLoading()
})

async function handleInit() {
  const buyLibRes = await buyLibList({ user_id: store.userInfo._id })
  const buyLibs = buyLibRes.data || []

  tabList.value = buyLibs.map((item) => {
    return {
      lib_name: item.lib_name,
      lib_id: item.lib_id
    }
  })
  tabList.value.unshift({ lib_name: '全部', lib_id: '' })

  libMap.value = buyLibs.reduce((acc, cur) => {
    acc[cur.lib_id] = cur.lib_name
    cur.lib_chapter?.forEach((it) => {
      acc[it.key] = it.value
    })
    return acc
  }, {})
}

function refreshOK() {
  // 下拉刷新时清空数据
  favExamData.value = []
  // 置空编辑选中数组
  editList.value = []
}

function queryRes(e) {
  // 数据追加
  const queryData = e.data || []
  favExamData.value = favExamData.value.concat(queryData)
}

const isEdit = ref(false)
function onEdit() {
  isEdit.value = !isEdit.value
  if (!isEdit.value) {
    // 置空编辑选中数组
    editList.value = []
  }
}

const editList = ref([])
function changeCheck(e) {
  const { checked, info } = e
  // checked为true时，向editList中添加项，否则删除
  if (checked) {
    editList.value.push(info)
  } else {
    const findIndex = editList.value.findIndex((item) => item == info)
    editList.value.splice(findIndex, 1)
  }
}

function onDelete() {
  uni.showModal({
    title: '系统提示',
    content: '确定删除选中试题吗？',
    showCancel: true,
    success: async ({ confirm }) => {
      if (confirm) {
        const deleteRes = await favExamDelete({
          user_id: store.userInfo._id,
          exam_id: editList.value
        })
        uni.showToast({ title: deleteRes.message })
        pagingRef.value.reload()
        // 置空编辑选中数组
        editList.value = []
      }
    }
  })
}

const examLibName = ref('全部')
function onExam(item, index) {
  uni.navigateTo({
    url: '/uni_modules/sv-exam-plus/pages/exam/exam-simple',
    success(res) {
      res.eventChannel.emit('e-transmit-exams', {
        title: `收藏试题 - ${examLibName.value}`,
        item,
        index,
        data: cloneDeep(favExamData.value) // 深拷贝，防止数据污染
      })
    }
  })
}

function tapTab(e) {
  // 清空数组
  favExamData.value = []
  // 置空编辑选中数组
  editList.value = []
  // 更新参数
  dataParams.value['from_lib'] = e.lib_id
  examLibName.value = e.lib_name
  // 重载
  pagingRef.value.reload()
}
</script>

<style lang="scss">
.exam-fav {
  height: var(--page-notab-height);
  box-sizing: border-box;

  .sv-paging-header {
    height: 88rpx;
  }

  .sv-paging-list {
    height: calc(100% - 88rpx);

    .fav-exam-card {
      margin: 24rpx 24rpx 0 24rpx;
      border-radius: 20rpx;
      box-shadow: 2px 2px 4px rgba(0, 0, 0, 0.2);
      border-top: 1rpx solid rgba(255, 255, 255, 0.4);
      border-left: 1rpx solid rgba(255, 255, 255, 0.4);
      backdrop-filter: blur(8px) brightness(110%);
      overflow: hidden;

      .fav-exam-item {
        padding: 20rpx 24rpx;
        box-sizing: border-box;

        @include useTheme {
          background-color: getTheme('sv-card-color');
        }

        .fav-exam-item-title {
          height: 40rpx;
          margin-bottom: 20rpx;

          .type-tag {
            background-color: #01beff;
            color: #ffffff;
            padding: 2rpx 8rpx;
            font-size: 12px;
            border-radius: 8rpx;
          }
        }
      }
    }
  }
}
</style>
